from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from profile.models import *
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.contrib import auth
from django import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.utils.safestring import mark_safe
from django.shortcuts import get_object_or_404

class AddFriendForm(forms.Form):
    friend = forms.CharField()
    current_user = None
    def clean(self):
        try:
            cleaned_data = self.cleaned_data
            friend = cleaned_data.get("friend")

            friend = auth.models.User.objects.get(username=friend)

            if friend.pk==self.current_user.pk:
                raise forms.ValidationError(mark_safe('You can not be friends with yourself!  <img src="http://i.imgur.com/2IIwd.png" />'))
            elif friend.get_profile().friends.all().filter(id=self.current_user.get_profile().pk).exists():
                raise forms.ValidationError("You are already friends with this user!")
            return cleaned_data
            
        except ObjectDoesNotExist:
            raise forms.ValidationError("User with given username could not be found.")

@login_required
def remove_POST(request):
    if request.method == "POST":
        remove(request, request.POST.get("user_id"))

    return HttpResponse(status=200)

@login_required
def add(request, user_id = None):
    if request.method == "POST":
        form = AddFriendForm(request.POST)
        form.current_user = request.user
        if form.is_valid():
            friend_username = form.cleaned_data['friend']
            new_friend = auth.models.User.objects.get(username=friend_username).get_profile()

            current_user = request.user.get_profile()
            current_user.friends.add(new_friend)
            current_user.save()
            form = AddFriendForm()
            form.current_user = request.user
            if not request.is_ajax():
                return HttpResponseRedirect(reverse('profile.detail.display'))
    elif user_id is not None:
        new_friend = get_object_or_404(UserProfile,pk=user_id)

        form = AddFriendForm()
        form.current_user = request.user
        form.cleaned_data = {}
        form.cleaned_data['friend'] = new_friend.user.username
        try:
            form.clean()
            current_user = request.user.get_profile()
            current_user.friends.add(new_friend)
            current_user.save()
            form = AddFriendForm()
            form.current_user = request.user
        except:
            pass
        if not request.is_ajax():
            return HttpResponseRedirect(reverse('profile.detail.display'))
        
    else:
        form = AddFriendForm()
        form.current_user = request.user

    return render_to_response( "add_friend.html", {'form':form},
            context_instance=RequestContext(request)
            )

@login_required
def remove(request, user_id):
    current_user = request.user.get_profile()
    remove_friend = get_object_or_404(UserProfile, pk=user_id)
    try:
        current_user.friends.remove(remove_friend)
    except:
        pass
    
    return HttpResponseRedirect(reverse('profile.detail.display'))

def friends_list(request, user_id):
    current_user = request.user
    user = get_object_or_404(UserProfile, pk=user_id)
    active_profile = False
    addable = False
    if current_user.is_authenticated():
        current_user_pk = current_user.get_profile().pk
        active_profile = (user.pk == current_user_pk)

    return render_to_response( "friends_list.html", 
            {   'current_user': user, 
                'active_profile':active_profile},
                context_instance=RequestContext(request))

